import {
  formatSeconds
} from '../../../utils/util.js'

let app = getApp()
Page({
  data: {
    spinShow: false,
    paperId: null,
    form: {},
    timer: null,
    doTime: 0,
    remainTime: 0,
    remainTimeStr: '',
    modalShow: false,
    result: 0,
    timeOutShow: false,
    // 新增：单题模式相关数据
    currentQuestionIndex: 0,
    currentQuestion: {}, // 当前题目对象
    allQuestions: [],
    userAnswers: {}, // 存储用户答案 {题号: 答案}
    answerSheetVisible: false, // 答题卡显示状态
    showSubmitConfirm: false // 显示提交确认弹窗
  },

  onLoad: function(options) {
    let type = options.type
    let _this = this
    _this.setData({
      spinShow: true
    });
    app.formPost('/api/wx/student/exampaper/select/' + type, null)
      .then(res => {
        _this.setData({
          spinShow: false
        });
        if (res.code === 1) {
          console.log(res.response)
          // 提取所有题目到一维数组
          const allQuestions = [];
          (res.response.titleItems || []).forEach(titleItem => {
            (titleItem.questionItems || []).forEach(question => {
              allQuestions.push({
                ...question,
                titleName: titleItem.name // 保留所属标题信息
              });
            });
          });

          _this.setData({
            form: res.response,
            paperId: res.response.id || type,
            remainTime: res.response.suggestTime * 60,
            allQuestions: allQuestions,
            currentQuestion: allQuestions[0] || {}, // 设置第一题
            userAnswers: {} // 初始化答案存储
          });
          _this.timeReduce()
        }
      }).catch(e => {
        _this.setData({
          spinShow: false
        });
        app.message(e, 'error')
      })
  },

  timeReduce() {
    let _this = this
    let timer = setInterval(function() {
      let remainTime = _this.data.remainTime
      if (remainTime <= 0) {
        _this.timeOut()
      } else {
        _this.setData({
          remainTime: remainTime - 1,
          remainTimeStr: formatSeconds(remainTime),
          doTime: _this.data.doTime + 1
        });
      }
    }, 1000)
    _this.setData({
      timer: timer
    });
  },

  onUnload() {
    clearInterval(this.data.timer)
  },

  returnRecord() {
    wx.reLaunch({
      url: '/pages/index/index',
    });
  },

  timeOut() {
    clearInterval(this.data.timer)
    this.setData({
      timeOutShow: true
    });
  },

  // 选择选项 - 新增的方法
  onOptionSelect: function(e) {
    const prefix = e.currentTarget.dataset.prefix;
    const currentQuestion = this.data.currentQuestion;
    const questionKey = `${currentQuestion.itemOrder}_${currentQuestion.id}_${currentQuestion.questionType}`;
    
    console.log('选择选项:', {
      prefix: prefix,
      questionKey: questionKey,
      currentQuestion: currentQuestion
    });
    
    // 更新用户答案
    const userAnswers = { ...this.data.userAnswers };
    userAnswers[questionKey] = prefix;
    
    this.setData({
      userAnswers: userAnswers
    });

    console.log('用户答案更新:', userAnswers);
  },

  // 选择答案 - 原有的方法（可以删除，因为现在用 onOptionSelect）
  onSelectAnswer: function(e) {
    const answer = e.detail.value;
    const currentQuestion = this.data.currentQuestion;
    const questionKey = `${currentQuestion.itemOrder}_${currentQuestion.id}_${currentQuestion.questionType}`;
    
    // 更新用户答案
    const userAnswers = { ...this.data.userAnswers };
    userAnswers[questionKey] = answer;
    
    this.setData({
      userAnswers: userAnswers
    });

    console.log('用户答案更新:', userAnswers);
  },

  // 上一题
  prevQuestion: function() {
    if (this.data.currentQuestionIndex > 0) {
      const newIndex = this.data.currentQuestionIndex - 1;
      this.setData({
        currentQuestionIndex: newIndex,
        currentQuestion: this.data.allQuestions[newIndex] || {}
      });
    }
  },

  // 下一题
  nextQuestion: function() {
    const { currentQuestionIndex, allQuestions } = this.data;
    if (currentQuestionIndex < allQuestions.length - 1) {
      const newIndex = currentQuestionIndex + 1;
      this.setData({
        currentQuestionIndex: newIndex,
        currentQuestion: allQuestions[newIndex] || {}
      });
    }
  },

  // 显示/隐藏答题卡
  toggleAnswerSheet: function() {
    this.setData({
      answerSheetVisible: !this.data.answerSheetVisible
    });
  },

  // 跳转到指定题目
  jumpToQuestion: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentQuestionIndex: index,
      currentQuestion: this.data.allQuestions[index] || {},
      answerSheetVisible: false
    });
  },

  // 检查是否所有题目都已作答
  checkAllAnswered: function() {
    const { allQuestions, userAnswers } = this.data;
    let unansweredCount = 0;
    
    allQuestions.forEach(question => {
      const questionKey = `${question.itemOrder}_${question.id}_${question.questionType}`;
      if (!userAnswers[questionKey]) {
        unansweredCount++;
      }
    });
    
    return {
      allAnswered: unansweredCount === 0,
      unansweredCount: unansweredCount
    };
  },

  // 自动补全未答题目
  autoCompleteUnanswered: function() {
    const { allQuestions, userAnswers } = this.data;
    const updatedAnswers = { ...userAnswers };
    
    allQuestions.forEach(question => {
      const questionKey = `${question.itemOrder}_${question.id}_${question.questionType}`;
      if (!updatedAnswers[questionKey]) {
        // 为未答题目设置一个不存在的选项 'X'
        updatedAnswers[questionKey] = 'X';
      }
    });
    
    return updatedAnswers;
  },

  // 显示提交确认弹窗
  showSubmitConfirm: function() {
    const checkResult = this.checkAllAnswered();
    
    if (checkResult.allAnswered) {
      // 所有题目都已作答，直接提交
      this.formSubmit();
    } else {
      // 有未答题目，显示确认弹窗
      this.setData({
        showSubmitConfirm: true,
        unansweredCount: checkResult.unansweredCount
      });
    }
  },

  // 隐藏提交确认弹窗
  hideSubmitConfirm: function() {
    this.setData({
      showSubmitConfirm: false
    });
  },

  // 强制提交（补全未答题目后提交）
  forceSubmit: function() {
    // 自动补全未答题目
    const completedAnswers = this.autoCompleteUnanswered();
    this.setData({
      userAnswers: completedAnswers,
      showSubmitConfirm: false
    });
    
    // 延迟一下确保状态更新后再提交
    setTimeout(() => {
      this.formSubmit();
    }, 100);
  },

  // 提交试卷
  formSubmit: function() {
    let _this = this
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    })

    // 构建提交数据
    const submitData = {
      id: this.data.paperId,
      doTime: this.data.doTime
    };

    // 将用户答案转换为表单格式
    Object.keys(this.data.userAnswers).forEach(key => {
      submitData[key] = this.data.userAnswers[key];
    });

    console.log('提交数据:', submitData);

    app.formPost('/api/wx/student/exampaper/answer/answerSubmit', submitData)
      .then(res => {
        if (res.code === 1) {
          _this.setData({
            modalShow: true,
            result: res.response
          });
        } else {
          app.message(res.message || '提交失败', 'error')
        }
        wx.hideLoading()
      }).catch(e => {
        wx.hideLoading()
        app.message(e, 'error')
      })
  },

  // 在答题卡中提交试卷
  submitFromAnswerSheet: function() {
    this.setData({
      answerSheetVisible: false
    });
    this.showSubmitConfirm();
  }
})